package com.sunjob.mroimg.service;

import cn.dev33.satoken.session.SaSession;
import cn.dev33.satoken.stp.StpUtil;
import com.sunjob.common.domain.img.SysImg;
import com.sunjob.common.domain.loginServer.SysUser;
import com.sunjob.common.util.MROUtils;
import com.sunjob.mroimg.mapper.ImgMapper;
import io.swagger.models.auth.In;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.PostConstruct;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.time.LocalDateTime;
import java.util.List;

/**
 * Created by IntelliJ IDEA.
 *
 * @Author : Wangzurong
 * @create 2022-08-09 9:12
 */
@Service
public class ImgServiceImpl implements ImgService {

@Autowired
ImgFileService imgFileService;
@Autowired
    ImgMapper imgMapper;
private String prefix;
@Value("${server.port}")
private String port;
@PostConstruct
private void init(){
    InetAddress address = null;
    try {
        address = InetAddress.getLocalHost();
        prefix = "http://"+address.getHostAddress()+":"+port+"/img/";
    } catch (UnknownHostException e) {
        e.printStackTrace();
    }
}
public String getPrefix(){
    return this.prefix;
}
    @Override
    public List<SysImg> pullImgBy(SysImg img) {
        return imgMapper.pullImgBy(img);
    }

    @Override
    public SysImg saveImg(SysImg img) {
        // 获取推送id
        Long loginId = StpUtil.getLoginIdAsLong();
        img.setImgPushId(loginId);
        img.setImgId(MROUtils.nextId());
        img.setImgSize(Long.valueOf(img.getData().length));
        LocalDateTime now = LocalDateTime.now();
        img.setCreateTime(now);
        img.setUpdateTime(now);
        SaSession tokenSession = StpUtil.getTokenSession();
        SysUser sysUser = (SysUser)tokenSession.get("userInfo");
        String loginName = sysUser.getLoginName();
        img.setCreateBy(loginName);
        img.setUpdateBy(loginName);
        img.setStatus(0);
        if(!imgFileService.saveToLocal(img)){
         return null;
        }
        img.setImgUrl(img.getImgUrl());
        Integer i = imgMapper.saveImg(img);
        if(i==0){
            return null;
        }
        return img;
    }

    @Override
    public List<SysImg> queryAllImg() {
        return imgMapper.queryAllImg();
    }

    @Override
    public SysImg getImgById(Long imgId) {
        return imgMapper.getImgById(imgId);
    }
}
